<?php

namespace app\api\logic\xiluhouse;

use app\common\model\xiluhouse\RentalRequest;
use think\Db;
use think\Validate;
use think\exception\ValidateException;
use think\exception\PDOException;
use Exception;

class RentalRequestLogic
{
    /**
     * 查找最近的地铁站
     * @param float $lat 纬度
     * @param float $lng 经度
     * @return array|null 返回最近的地铁站信息，如果没有符合条件的则返回null
     */
    private function findNearestSubway($lat, $lng)
    {
        if (empty($lat) || empty($lng)) {
            return null;
        }

        // 获取配置的地铁房距离
        $subwayDistance = Db::name('xiluhouse_config')
            ->where('name', 'subway_distance')
            ->value('value');
        
        if (empty($subwayDistance)) {
            $subwayDistance = 5000; // 默认5000米
        }

        // 获取所有地铁站点
        $subwayStations = Db::name('xiluhouse_subway_platform')
            ->alias('p')
            ->join('xiluhouse_subway s', 'FIND_IN_SET(s.code, p.subways)')
            ->field('p.id as station_id, p.name as station_name, p.lat, p.lng, s.id as line_id, s.name as line_name')
            ->select();

        $nearestStation = null;
        $minDistance = $subwayDistance;

        foreach ($subwayStations as $station) {
            // 确保经纬度是数值类型
            $stationLat = floatval($station['lat']);
            $stationLng = floatval($station['lng']);
            
            if ($stationLat && $stationLng) {
                $distance = get_distance($lat, $lng, $stationLat, $stationLng);
                if ($distance <= $minDistance) {
                    $minDistance = $distance;
                    $nearestStation = [
                        'metro_line_id' => $station['line_id'],
                        'metro_station_id' => $station['station_id'],
                        'metro_line_name' => $station['line_name'],
                        'metro_station_name' => $station['station_name'],
                        'distance' => $distance
                    ];
                }
            }
        }

        return $nearestStation;
    }

    /**
     * 新增求租信息
     */
    public function add($params, $user)
    {
        $validate = new Validate([
            'name|用户名称'           => 'require|max:50',
            'mobile|手机号'          => 'require|mobile',
            'gender|性别'            => 'number|in:0,1,2',
            'room_num|室数'         => 'require|number|egt:1',
            'ting_num|厅数'         => 'require|number|egt:0',
            'wei_num|卫数'          => 'require|number|egt:0',
            'in_time|用房时间'        => 'require|date',
            'budget|租房预算'         => 'require|float|gt:0',
            'address|意向区域'        => 'require|max:255',
            'requirements|其他要求'    => 'max:50',
            // 'province_id|省份'       => 'require|number|gt:0',
            // 'city_id|城市'          => 'require|number|gt:0',
            // 'district_id|区县'      => 'require|number|gt:0',
            'lat|纬度'              => 'float',
            'lng|经度'              => 'float'
        ]);

        if(!$validate->check($params)){
            return ['code'=>0, 'msg'=>$validate->getError()];
        }

        // 设置默认性别为不限
        if(!isset($params['gender'])){
            $params['gender'] = 0;
        }

        // 如果提供了经纬度，查找最近的地铁站
        if (!empty($params['lat']) && !empty($params['lng'])) {
            $nearestSubway = $this->findNearestSubway($params['lat'], $params['lng']);
            if ($nearestSubway) {
                $params['metro_line_id'] = $nearestSubway['metro_line_id'];
                $params['metro_station_id'] = $nearestSubway['metro_station_id'];
            }
        }

        $params['user_id'] = $user['id'];
        $params['is_delete'] = 2; // 设置未删除状态
        $params['apply_status'] = 2; // 设置为待审核状态
        
        $model = new RentalRequest();
        Db::startTrans();
        try {
            $ret = $model->allowField(true)->save($params);
            if(!$ret){
                throw new Exception('保存失败');
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
        Db::commit();
        return ['code'=>1, 'msg'=>'success', 'data'=>$model];
    }

    /**
     * 修改求租信息
     */
    public function edit($params, $user)
    {
        if(empty($params['id'])){
            return ['code'=>0, 'msg'=>'参数错误'];
        }

        $validate = new Validate([
            'name|用户名称'           => 'require|max:50',
            'mobile|手机号'          => 'require|mobile',
            'gender|性别'            => 'number|in:0,1,2',
            'room_num|室数'         => 'require|number|egt:1',
            'ting_num|厅数'         => 'require|number|egt:0',
            'wei_num|卫数'          => 'require|number|egt:0',
            'in_time|用房时间'        => 'require|date',
            'budget|租房预算'         => 'require|float|gt:0',
            'address|意向区域'        => 'require|max:255',
            'requirements|其他要求'    => 'max:50',
            // 'province_id|省份'       => 'require|number|gt:0',
            // 'city_id|城市'          => 'require|number|gt:0',
            // 'district_id|区县'      => 'require|number|gt:0',
            'lat|纬度'              => 'float',
            'lng|经度'              => 'float'
        ]);

        if(!$validate->check($params)){
            return ['code'=>0, 'msg'=>$validate->getError()];
        }

        // 设置默认性别为不限
        if(!isset($params['gender'])){
            $params['gender'] = 0;
        }

        $where = [
            'id' => $params['id'],
            'user_id' => $user['id'],
            'is_delete' => 2 // 只能修改未删除的记录
        ];
        $model = RentalRequest::where($where)->find();
        if(!$model){
            return ['code'=>0, 'msg'=>'记录不存在或无权操作'];
        }

        // 如果提供了经纬度，重新查找最近的地铁站
        if (!empty($params['lat']) && !empty($params['lng'])) {
            $nearestSubway = $this->findNearestSubway($params['lat'], $params['lng']);
            if ($nearestSubway) {
                $params['metro_line_id'] = $nearestSubway['metro_line_id'];
                $params['metro_station_id'] = $nearestSubway['metro_station_id'];
            } else {
                // 如果没有找到符合条件的地铁站，清空地铁相关信息
                $params['metro_line_id'] = 0;
                $params['metro_station_id'] = 0;
            }
        }

        // 修改后重新设置为待审核状态
        $params['apply_status'] = 2;
        $params['apply_time'] = 0;
        $params['apply_reason'] = '';

        Db::startTrans();
        try {
            $ret = $model->allowField(true)->save($params);
            if(!$ret){
                throw new Exception('保存失败');
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
        Db::commit();
        return ['code'=>1, 'msg'=>'success', 'data'=>$model];
    }

    /**
     * 删除求租信息
     */
    public function delete($params, $user)
    {
        if(empty($params['id'])){
            return ['code'=>0, 'msg'=>'参数错误'];
        }

        $where = [
            'id' => $params['id'],
            'user_id' => $user['id'],
            'is_delete' => 2 // 只能删除未删除的记录
        ];
        $model = RentalRequest::where($where)->find();
        if(!$model){
            return ['code'=>0, 'msg'=>'记录不存在或无权操作'];
        }

        Db::startTrans();
        try {
            // 执行软删除
            $ret = $model->save(['is_delete' => 1]);
            if(!$ret){
                throw new Exception('删除失败');
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            return ['code'=>0, 'msg'=>$e->getMessage()];
        }
        Db::commit();
        return ['code'=>1, 'msg'=>'success'];
    }

    /**
     * 获取求租信息列表（所有人的）
     * @param array $params 参数
     * - metro_line_id 地铁线路ID
     * - metro_station_id 地铁站ID
     * - min_price 最小租金
     * - max_price 最大租金
     * - min_room_num 最小户型
     * - max_room_num 最大户型
     * - ting_num 厅数
     * - wei_num 卫数
     * @return array
     */
    public function getList($params)
    {
        $page = !empty($params['page']) ? intval($params['page']) : 1;
        $limit = !empty($params['limit']) ? intval($params['limit']) : 10;

        $where = [];
        $where['status'] = 'normal';
        $where['is_delete'] = 2; // 只查询未删除的记录
        $where['apply_status'] = 1; // 只查询审核通过的记录

        // 地铁线路筛选
        if (!empty($params['metro_line_id'])) {
            $where['metro_line_id'] = intval($params['metro_line_id']);
        }

        // 地铁站筛选
        if (!empty($params['metro_station_id'])) {
            $where['metro_station_id'] = intval($params['metro_station_id']);
        }

        // 租金范围筛选
        if (!empty($params['min_price'])) {
            if (!isset($where['budget'])) {
                $where['budget'] = [];
            }
            if (!is_array($where['budget'])) {
                $where['budget'] = [$where['budget']];
            }
            $where['budget'][] = ['>=', floatval($params['min_price'])];
        }
        
        if (!empty($params['max_price']) && $params['max_price'] != -1) {
            if (!isset($where['budget'])) {
                $where['budget'] = ['<=', floatval($params['max_price'])];
            } else {
                if (!is_array($where['budget'])) {
                    $where['budget'] = [$where['budget']];
                }
                $where['budget'][] = ['<=', floatval($params['max_price'])];
            }
        }

        // 户型筛选
        if (!empty($params['min_room_num'])) {
            if (!isset($where['room_num'])) {
                $where['room_num'] = [];
            }
            if (!is_array($where['room_num'])) {
                $where['room_num'] = [$where['room_num']];
            }
            $where['room_num'][] = ['>=', intval($params['min_room_num'])];
        }
        
        if (!empty($params['max_room_num']) && $params['max_room_num'] != -1) {
            if (!isset($where['room_num'])) {
                $where['room_num'] = ['<=', intval($params['max_room_num'])];
            } else {
                if (!is_array($where['room_num'])) {
                    $where['room_num'] = [$where['room_num']];
                }
                $where['room_num'][] = ['<=', intval($params['max_room_num'])];
            }
        }

        if (!empty($params['ting_num'])) {
            $where['ting_num'] = intval($params['ting_num']);
        }
        if (!empty($params['wei_num'])) {
            $where['wei_num'] = intval($params['wei_num']);
        }

        // 按创建时间倒序
        $order = 'createtime DESC';

        $fields = 'id,user_id,room_num,ting_num,wei_num,in_time,budget,address,requirements,createtime,apply_status,apply_time,apply_reason,metro_line_id,metro_station_id';

        $list = RentalRequest::field($fields)
            ->with(['user' => function($query){
                $query->field('id,nickname,avatar');
            }])
            ->where($where)
            ->order($order)
            ->paginate($limit);

        if($list){
            foreach($list as $key => $val){
                // 发布时间
                $list[$key]['createtime'] = !empty($val['createtime']) ? date('m-d H:i', $val['createtime']) : '';
                // 审核时间
                $list[$key]['apply_time'] = !empty($val['apply_time']) ? date('Y-m-d H:i', $val['apply_time']) : '';
            }
        }

        return $list;
    }

    /**
     * 获取我的求租列表
     */
    public function getMyList($params, $user)
    {
        $page = !empty($params['page']) ? intval($params['page']) : 1;
        $limit = !empty($params['limit']) ? intval($params['limit']) : 10;

        $where = [];
        // 只查看自己的记录
        $where['user_id'] = $user['id'];
        $where['status'] = 'normal';
        $where['is_delete'] = 2; // 只查询未删除的记录

        // 按创建时间倒序
        $order = 'createtime DESC';

        $fields = 'id,user_id,room_num,ting_num,wei_num,in_time,budget,address,requirements,createtime,apply_status,apply_time,apply_reason';
        $list = RentalRequest::field($fields)
            ->where($where)
            ->with(['user' => function($query){
                $query->field('id,nickname,avatar');
            }])
            ->order($order)
            ->paginate($limit);
        
        if($list){
            foreach($list as $key => $val){
                // 发布时间
                $list[$key]['createtime'] = !empty($val['createtime']) ? date('m-d H:i', $val['createtime']) : '';
                // 审核时间
                $list[$key]['apply_time'] = !empty($val['apply_time']) ? date('Y-m-d H:i', $val['apply_time']) : '';
            }
        }

        return $list;
    }

    /**
     * 获取求租信息详情
     * @param array $params 参数
     * @param array|null $currentUser 当前登录用户，未登录时为null
     */
    public function detail($params, $currentUser = null)
    {
        if(empty($params['id'])){
            return ['code'=>0, 'msg'=>'参数错误'];
        }

        $where = [
            'id' => $params['id'],
            'status' => 'normal',
            'is_delete' => 2 // 只能查看未删除的记录
        ];

        // 如果不是本人查看，则只能查看已审核的记录
        if (!$currentUser || !isset($currentUser['id'])) {
            $where['apply_status'] = 1; // 未登录用户只能查看已审核的记录
        }
        
        $info = RentalRequest::with(['user' => function($query){
            $query->field('id,nickname,avatar');
        }])->where($where)->find();

        if(!$info){
            return ['code'=>0, 'msg'=>'记录不存在'];
        }

        // 判断是否是本人查看
        $isSelf = $currentUser && isset($currentUser['id']) && $info['user_id'] == $currentUser['id'];

        // 处理返回数据
        $data = [
            'id' => $info['id'],
            'user_id' => $info['user_id'],
            'room_type_text' => $info->room_type_text,
            'room_num' => $info['room_num'],
            'ting_num' => $info['ting_num'],
            'wei_num' => $info['wei_num'],
            'in_time' => $info['in_time'],
            'budget' => $info['budget'],
            'address' => $info['address'],
            'requirements' => $info['requirements'],
            'createtime' => !empty($info['createtime']) ? date('m-d H:i', $info['createtime']) : '',
            'user' => $info['user'],
            'apply_status' => $info['apply_status'],
            'apply_status_text' => $info->apply_status_text
        ];

        // 如果是本人查看，显示更多信息
        if ($isSelf) {
            $data = array_merge($data, [
                'name' => $info['name'],
                'mobile' => $info['mobile'],
                'gender' => $info['gender'],
                'gender_text' => $info->gender_text,
                'apply_time' => !empty($info['apply_time']) ? date('Y-m-d H:i', $info['apply_time']) : '',
                'apply_reason' => $info['apply_reason'],
                'status' => $info['status'],
                'status_text' => $info->status_text
            ]);
        }

        // 如果有地铁信息，添加地铁相关字段
        if (!empty($info['metro_line_id']) || !empty($info['metro_station_id'])) {
            $data['metro_line_id'] = $info['metro_line_id'];
            $data['metro_station_id'] = $info['metro_station_id'];
        }

        return ['code'=>1, 'msg'=>'success', 'data'=>$data];
    }

    /**
     * 获取求租用户联系方式
     * @param array $params 参数
     * @param array $user 当前登录用户
     * @return array
     */
    public function getContact($params, $user)
    {
        if(empty($params['id'])){
            return ['code'=>0, 'msg'=>'参数错误'];
        }

        // 检查用户是否发布过房源
        $hasPublishedRental = Db::name('xiluhouse_rental')
            ->where([
                'user_id' => $user['id'],
                'status' => 'normal',
                'deletetime' => null,
                'apply_status' => 1 // 已审核通过的房源
            ])
            ->count();

        if (!$hasPublishedRental) {
            return ['code'=>603, 'msg'=>'只有发布过房源的用户才能查看联系方式'];
        }

        $where = [
            'id' => $params['id'],
            'status' => 'normal',
            'is_delete' => 2, // 只能查看未删除的记录
            'apply_status' => 1 // 只能查看已审核的记录
        ];
        
        $info = RentalRequest::where($where)->find();
        if(!$info){
            return ['code'=>0, 'msg'=>'记录不存在或未通过审核'];
        }

        // 不能查看自己的联系方式（因为自己已经知道）
        if ($info['user_id'] == $user['id']) {
            return ['code'=>0, 'msg'=>'不能查看自己的联系方式'];
        }

        // 获取联系方式
        $contact = [
            'name' => $info['name'],
            'mobile' => $info['mobile'],
            'gender' => $info['gender'],
            'gender_text' => $info->gender_text,
            'room_type' => $info->room_type_text,
            'in_time' => $info['in_time'],
            'budget' => $info['budget'],
            'address' => $info['address'],
            'requirements' => $info['requirements']
        ];

        // 记录查看记录（可选，如果需要记录谁查看了联系方式）
        // TODO: 如果需要记录查看历史，可以在这里添加记录

        return ['code'=>1, 'msg'=>'success', 'data'=>$contact];
    }
} 